package com.eportal.struts.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.ExceptionHolder;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


/**
 * Created by smzhang on 2016/1/13.
 * 自定义异常处理类
 */
public class ErrorInterceptor extends AbstractInterceptor {
	
	private static Logger log = Logger.getLogger(ErrorInterceptor.class);
	
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String result;

        try {
            result = invocation.invoke();
        } catch (Exception e) {
        	log.error(this,e);
            Object action = invocation.getAction();
            if (action instanceof ValidationAware) {
                ValidationAware va = (ValidationAware) action;
                if (va.hasFieldErrors()) {
                    StringBuffer sb = new StringBuffer();
                    Map<String, List<String>> errros = va.getFieldErrors();
                    for (Entry<String, List<String>> error : errros.entrySet()){
                        sb.append(error.getValue() + "</br>");
                    }
                    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    Map map = new HashMap();
                    map.put("code", -1);
                    map.put("msg", sb.toString());
                    JSONObject json = JSONObject.fromObject(map);
                    out.write(json.toString());
                    out.close();
                } else {
                    return "exception";
                }
            }
        }
        return null;
    }
}